package com.gary.websocket.server;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * websocket 核心处理类
 * @author pengrui
 * @date 2021/2/19 - 9:32
 */
@ServerEndpoint("/webSocket/{sid}")
@Component
public class WebSocketServer {
    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static AtomicInteger onlineNum = new AtomicInteger();

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
     */
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    /**
     *  发送消息
     * @param session
     * @param message
     */
    public void sendMessage(Session session, String message) throws IOException {
        if (session != null) {
            synchronized (session) {
                System.out.println("发送数据" + message);
                session.getBasicRemote().sendText(message);
            }
        }
    }

    /**
     *  给指定用户发送信息
     * @param userId
     * @param message
     */
    public void sendInfo(String userId, String message) {
        Session session = sessionPools.get(userId);
        if (session != null) {
            try {
                sendMessage(session, message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("暂无用户");
        }
    }

    /**
     * 建立链接成功调用
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String userId) {
        sessionPools.put(userId, session);
        addOnlineCount();
        System.out.println(userId+"加入链接，当前连接数" + onlineNum);
        sendInfo(userId, "ggb");
    }

    /**
     *  断开链接
     * @param userId
     */
    @OnClose
    public void onClose(@PathParam("sid") String userId) {
        sessionPools.remove(userId);
        subOnlineCount();
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("发生错误");
        throwable.printStackTrace();
    }

    /**
     *  在线连接数自增
     */
    private static void addOnlineCount() {
        onlineNum.incrementAndGet();
    }

    /**
     *  在线链接数自减
     */
    private static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }
}
